<template>
  <div class="dropdown" ref="dropdownRef">
    <a href="#" class="btn btn-outline-light my-2 dropdown-toggle" @click.prevent="toggleOpen"
    >{{ title }}</a>
    <ul class="dropdown-menu" :style="{display:'block'}" v-if="isOpen">
      <!--插值是dropdown-item组件数据-->
      <slot></slot>
    </ul>
  </div>
</template>

<script lang="ts">
import {defineComponent, ref, watch} from 'vue'
import useClickOutside from "@/hooks/useClickOutside";


export default defineComponent({
  name: "DropDown",
  props: {
    title: {
      type: String,
      required: true
    }
  },
  setup() {
    //登录后的二级菜单
    const isOpen = ref(false)
    //控制下拉列表的显示和隐藏
    const toggleOpen = () => {
      isOpen.value = !isOpen.value
    }

    //获取 class="dropdown"里面的数据展开的元素
    const dropdownRef = ref<null | HTMLElement>(null)
    // console.log(dropdownRef)

    const isClickOutSide = useClickOutside(dropdownRef)
    watch(isClickOutSide, () => {
      if (isOpen.value && isClickOutSide.value) {
        isOpen.value = false
      }
    })
    return {
      isOpen,
      toggleOpen,
      dropdownRef
    }
  }

})
</script>

<style scoped>

</style>